package com.dh.blog.handler.parser;

import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.springframework.stereotype.Component;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@Component
public class XPathParser implements Parser{
	//whether use the NameSpaceContext
	private static final boolean isNameContext = false;
	
	private static final String nameContext = "http://davidhua.top/blog/article";
	
	private static XPath xpath; 
	
	static{
		XPathFactory factory = XPathFactory.newInstance();
		xpath = factory.newXPath();
		if(isNameContext){
			xpath.setNamespaceContext(new BlogNameSpaceContext());
		}
	}
	public String evalString(String expr, Object obj) throws Exception{
		return (String)xpath.evaluate(expr,obj,XPathConstants.STRING);
	}

	public Boolean evalBoolean(String expr, Object obj) throws Exception {
		return (Boolean)xpath.evaluate(expr,obj,XPathConstants.BOOLEAN);
	}

	public Double evalNum(String expr, Object obj) throws Exception{
		return (Double)xpath.evaluate(expr, obj, XPathConstants.NUMBER);
	}

	public Node evalNode(String expr, Object obj) throws Exception{
		return (Node)xpath.evaluate(expr, obj, XPathConstants.NODE);
	}

	public NodeList evalNodeList(String expr, Object obj) throws Exception{
		return (NodeList)xpath.evaluate(expr, obj, XPathConstants.NODESET);
	}

	public Node evalRoot(Object obj) throws Exception{
		return (Node)xpath.evaluate("/*", obj, XPathConstants.NODE);
	}
	static class BlogNameSpaceContext implements NamespaceContext{
	
		public String getNamespaceURI(String prefix) {
			if(null == prefix){
				throw new NullPointerException("prefix is in needed!");
			}
			if(prefix.equals("blog")){
				return nameContext;
			}
			return XMLConstants.NULL_NS_URI;
		}

		public String getPrefix(String namespaceURI) {
			return null;
		}

		@SuppressWarnings("rawtypes")
		public Iterator getPrefixes(String namespaceURI) {
			return null;
		}
		
	}
}
